package com.zj.leetcode.medium.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: algorithm
 * @description: 求根节点到叶节点数字之和
 * 129 sum-root-to-leaf-numbers
 * @author: Zhang Bo
 * @create: 2022-06-24 10:37:06
 **/
public class SumRootToLeafNumbers {
    public static void main(String[] args) {
        Solution solution = new SumRootToLeafNumbers().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        List<Integer> list = new ArrayList<>();

        public int sumNumbers(TreeNode root) {
            if (root == null) {
                return 0;
            }
            this.dfs(root, "" + root.val);

            return list.stream()
                    .reduce(Integer::sum)
                    .orElse(0);
        }

        private void dfs(TreeNode node, String str) {

            if (node.left != null) {
                this.dfs(node.left, str + node.left.val);
            }

            if (node.right != null) {
                this.dfs(node.right, str + node.right.val);
            }
            if (node.left == null && node.right == null) {
                System.out.println(str);
                list.add(Integer.parseInt(str));
            }

        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}